package nth.bananas.solving;

import java.util.Set;

public class PuzzleRules {
	
	/**
	 * Checks if this puzzle is a valid solution. 
	 * This is true if every piece shares an edge (not corner) with another piece,
	 * and every word (reading down and to the left) is valid. 
	 * 
	 * @param p	the puzzle to check
	 * @return	true if the solution is legal
	 */
	public static boolean isValid(Puzzle p) {
		return isValidWords(p) && isValidConnected(p);
	}

	public static boolean isValidWords(Puzzle p) {
		boolean result = true;
		Set<String> words = PuzzleUtils.findWords(p);
		
		for (String s : words) {
			if (! WordUtility.isValidWord(s)) {
				result = false;
			}
		}
				
		return result;
	}

	public static boolean isValidConnected(Puzzle p) {
		boolean result = true;

		for (GridSpot<Letter> gs : p.getSpots()) {
			if (! (    p.spotExists(gs.getX(), gs.getY() + 1)
					|| p.spotExists(gs.getX(), gs.getY() - 1)
					|| p.spotExists(gs.getX() + 1, gs.getY())
					|| p.spotExists(gs.getX() - 1, gs.getY()))) {
				result = false;
			}
		}


		return result;
	}	

}
